package com.wxy.config;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.UUID;

/**
 * @author 47868
 * 设置消息发送者确认机制
 */
@Component
public class RabbitMqProducer {
    private static final Logger log = LoggerFactory.getLogger(RabbitMqProducer.class);
    private final RabbitTemplate rabbitTemplate;

    @Autowired
    public RabbitMqProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public void sendMapMessage(String exchange, String routingKey, Map<String, Object> mapMessage) {
        // 为每条消息生成唯一的关联 ID
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());

        // 发送消息
        rabbitTemplate.convertAndSend(exchange, routingKey, mapMessage,message -> {
            message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            return message;
        },correlationData);
        log.debug("消息已发送，ID: {}", correlationData.getId());
    }
}